<!--
 * @Description: 
 * @version: 
 * @Author: 尹鹏孝
 * @Date: 2022-01-25 09:31:56
 * @LastEditors: 尹鹏孝
 * @LastEditTime: 2022-01-25 09:39:38
-->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>求四数之和</title>
</head>

<body>
    <script>
        var fourSum = function (nums, target) {
            let len = nums.length;
            if (len < 4) {
                return []
            }
            nums.sort((a, b) => a - b);
            const res = [];
            for (let i = 0; i < len - 3; i++) {
                if (nums[i] > 0 && nums[i - 1] === nums[i]) {
                    continue;
                }
                for (let j = i + 1; j < len - 2; j++) {
                    if (j > i + 1 && nums[j] === nums[j - 1]) {
                        continue;
                    }
                    let l = j + 1, r = j - 1;
                    while (l < r) {
                        const sum = nums[i] + nums[j] + nums[l] + nums[r];
                        if (sum < target) {
                            l++;
                            continue;
                        }
                        if (sum > target) {
                            r--;
                            continue;
                        }
                        res.push(nums[i], nums[j], nums[l], nums[r]);
                        while (l < r && nums[l] === nums[++l]) {

                        }
                        while (l < r && nums[l] === nums[--r]) {

                        }
                    }
                }
            }
        }
    </script>
</body>

</html>